#include "Common.hpp"
#include "Protocal.hpp"
#include "Socket.hpp"


void Usage(std::string proc)
{
    std::cerr << "命令输入格式错误! Usage: " << proc << " ip" << " port" << std::endl;
}

void GetDataFromStd(int *x, int *y, char *oper)
{
    std::cout << "please inter x: " << std::endl;
    std::cin >> *x;
    std::cout << "please inter y: " << std::endl;
    std::cin >> *y;
    std::cout << "please inter oper: " << std::endl;
    std::cin >> *oper;
}

//./tcpclient 127.0.0.1 8080
int main(int argc, char *argv[])
{

    // 检查输入格式
    // ./tcpclient 127.0.0.1 8080
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }

    std::string server_ip = argv[1];      // 获取目标服务器IP
    int server_port = std::stoi(argv[2]); // 获取目标服务器端口

    std::shared_ptr<Socket> client = std::make_shared<TcpSocket>(); // 创建client套接字指针
    client->BuildTcpClientSocketMethod();                        // 创建client socket

    int ret = client->Connect(server_ip, server_port); // 连接目标服务器
    if (ret != 0)
    {
        // 连接失败
        std::cerr << "connect error, 连接目标服务器失败!" << std::endl;
        exit(CONNECT_ERR);
    }

    
    std::unique_ptr<Protocol> protocal = std::make_unique<Protocol>(); // 创建协议对象
    std::string resp_buffer; // 创建接收返回结果的buffer
    // 获取用户输入数据
    while (1)
    {
        int x, y;
        char oper;
        GetDataFromStd(&x, &y, &oper);

        // 构造请求数据
        std::string req_str = protocal->BuildRequestString(x, y, oper);
        /* std::cout << "------------------encode req string ------------------------" << std::endl;
        std::cout << req_str << std::endl;
        std::cout << "------------------------------------------------------------" << std::endl; */

        //发送数据s
        client->Send(req_str);

        // 接收返回结果, 反序列化数据 和 序列化数据
        Response resp;
        int ret = protocal->GetResponse(client, resp_buffer, &resp);
        if(ret == false)
        {
            // 接收失败
            break;
        }
        // 打印返回结果
        resp.ShowResult();
    }

    return 0;
}
